#!/usr/bin/perl

use Time::Interval;

sub get_now_time
{
    my ($sec, $min, $hour, $day, $mon, $year, $weekday, $yeardate, $savinglightday) = (localtime(time));

    $sec  = ($sec < 10) ? "0$sec" : $sec;
    $min  = ($min < 10) ? "0$min" : $min;
    $hour = ($hour < 10) ? "0$hour" : $hour;
    $day  = ($day < 10) ? "0$day" : $day;
    $mon  = ($mon < 9) ? "0".($mon+1) : ($mon+1);
    $year += 1900;

    my $today = "$year-$mon-$day $hour:$min:$sec";
    return $today;
}


open(FILE, "/var/run/configagent.pid") or die "pid file open error!\n";
my $cfgagentpid = scalar <FILE>;
my $cgpid = substr($cfgagentpid, 0, length($cfgagentpid)-1);
close(FILE);
print "PID: $cgpid\n";

system("killall -9 tcpdump");
my $captime = get_now_time();
my $capname = $captime;
$capname =~ tr/:/_/;
$capname =~ tr/" "/_/;
my $capfile = sprintf("/home/apuadmin/baiyu/9kcap.%s.pcap", $capname);
my $capexec = system("tcpdump -ni lo port 9000 -s 512 -w $capfile >/dev/null 2>&1 &");

open(LOGFILE, ">/var/log/configagent.monitport.$cgpid") or die "open log error!\n";

while (1)
{
	my $now = get_now_time();
	print LOGFILE "\n$now\n";

	my $delta = getInterval($now, $captime, 0);
	if ($$delta{minutes} >= 1) {
		system("killall -9 tcpdump");
		$captime = get_now_time();
		$capname = $captime;
		$capname =~ tr/:/_/;
		$capname =~ tr/" "/_/;
		$capfile = sprintf("/home/apuadmin/baiyu/9kcap.%s.pcap", $capname);
		$capexec = system("tcpdump -ni lo port 9000 -s 512 -w $capfile >/dev/null 2>&1 &");
	}

	my $monit = `lsof -np $cgpid | grep IPv4 | grep '9000->'`;
	print LOGFILE "$monit\n";

	if (length($monit) > 2)
	{
		my $colon = rindex($monit, ":");
		my $space = rindex($monit, " ");
		my $connpid = substr($monit, $colon+1, $space-$colon);
		#print "$connpid\n";
		my $connprocess = `lsof -ni :$connpid`;
		$ret = $?;
		print LOGFILE "[$ret]: $connprocess\n";
		if ($ret == 256) {
			print LOGFILE "RERUN IT !\n";
			$connprocess = `lsof -ni :$connpid`;
			$ret = $?;
			print LOGFILE "[$ret]: $connprocess\n";
		}
	}
	sleep(2);
}

close(LOGFILE);

